package com.voice.call.service.impl;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import voice.voice.call.cache.ConfigSystemCache;

import com.voice.call.common.Const;
import com.voice.call.common.Result;
import com.voice.call.common.ResultEnum;
import com.voice.call.entity.AdvertOperateLog;
import com.voice.call.entity.GlobalConfig;
import com.voice.call.entity.SupportMcc;
import com.voice.call.entity.TaskIntegral;
import com.voice.call.entity.TaskLog;
import com.voice.call.mapper.TaskIntegralMapper;
import com.voice.call.service.AdvertOperateLogService;
import com.voice.call.service.ConsumeLogService;
import com.voice.call.service.GlobalConfigService;
import com.voice.call.service.SupportMccService;
import com.voice.call.service.TaskIntegralService;
import com.voice.call.service.TaskLogService;
import com.voice.call.service.UserAccountService;
import com.voice.call.utils.DateUtil;
import com.voice.call.utils.StringUtil;

@Service
public class TaskIntegralServiceImpl implements TaskIntegralService{
	
	private final Logger log = LoggerFactory.getLogger(TaskIntegralServiceImpl.class);
	
	@Resource
	private TaskIntegralMapper taskIntegralMapper;
	
	@Resource
	private TaskLogService taskLogService;
	
	@Resource
	private ConfigSystemCache configSystemCache;
	
	@Resource
	private ConsumeLogService consumeLogService;
	
	@Resource
	private GlobalConfigService globalConfigService;
	
	@Resource
	private UserAccountService userAccountService;
	
	@Resource
	private SupportMccService supportMccService;
	
	@Resource
	private AdvertOperateLogService advertOperateLogService;
	
	//获取lucky credit列表
	@Override
	public Result getLuckyCreditList(Integer user_id){
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("category", Const.TASK_LUCKY_CREDIT);
		params.put("status", Const.Y);
		List<TaskIntegral> checkList = taskIntegralMapper.list(params);
		List<Map<String, Object>> rsList = new ArrayList<Map<String,Object>>();
		if(checkList!=null && !checkList.isEmpty()){
			
			for (TaskIntegral task : checkList) {
				Map<String, Object> itemMap = new HashMap<String, Object>();
				itemMap.put("id", task.getId());//任务id
				itemMap.put("name", task.getName());//名称
				itemMap.put("integral", task.getIntegral());//积分
				rsList.add(itemMap);
			}
			
			
		}
		
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("total", taskLogService.getPlayLuckyCreditCount(user_id));
		rsMap.put("list", rsList);
		return new Result();
		
	}
	
	//lucky credit猜中积分赠送
	@Transactional
	@Override
	public	Result playLuckyCredit(Integer user_id,Integer taskId){
		
		if (consumeLogService.hasOverMaxIntegralLimit(user_id)) {
			log.info("超过当日获取积分最大限制");
			return new Result(ResultEnum.INTEGRAL_LIMIT_ERROR);
		}
		
		TaskIntegral entity = taskIntegralMapper.get(taskId);
		if(entity==null){
			log.info("未找到lucky credit id");
			return new Result(ResultEnum.FAILED);
		}
		
		//判断是否超过最大限制玩的次数
		int total = taskLogService.getPlayLuckyCreditCount(user_id); //获取今天玩的次数
		GlobalConfig config = globalConfigService.getConfigForKey(Const.GLOBAL_CATEGORY, Const.LUCKY_CREDIT_LIMIT);
		if(config!=null){
			if(total>=Integer.valueOf(config.getValue()).intValue()){
				log.info("lucky credit 超过最大可玩次数");
				return new Result(ResultEnum.LUCKY_CREDIT_LIMIT);
			}
		}
		
		
		TaskLog taskLog = new TaskLog();
		taskLog.setUserId(user_id);
		taskLog.setTaskId(taskId);
		taskLog.setIntegral(entity.getIntegral());
		taskLog.setCategory(entity.getCategory());
		taskLog.setCtime(new Date());
		if(taskLogService.addTaskLog(taskLog)){
			
			if(userAccountService.updateAccountBlance(user_id, taskLog.getIntegral(), true)){
				log.info("帐户添加老虎机积分成功");
			}else {
				log.error("帐户添加老虎机积分失败");
			}
			//添加消费记录
			consumeLogService.addConsumeLog(user_id, "lucky credit", Const.TASK_LUCKY_CREDIT,taskLog.getIntegral(),true, null);
			log.info("lucky credit猜中积分赠送成功");
			return new Result();
		}else{
			log.error("lucky credit猜中积分赠送失败");
			return new Result(ResultEnum.FAILED);
		}
		
	}
	
	//获取邀请类别相关的的任务
	@Override
	public	TaskIntegral getInviteCategory(String category){
		
		return this.getTaskIntegralForCateogry(category);
	}
	
	//获取某个类别的任务
	@Override
	public	TaskIntegral getTaskIntegralForCateogry(String category){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("category", category);
		params.put("status", Const.Y);
		List<TaskIntegral> checkList = taskIntegralMapper.list(params);
		if(checkList!=null && !checkList.isEmpty()){
			return checkList.get(0);
		}
		return null;
	}
	
	
	
	
	//获取激励视频广告/应用墙/等广告任务卡片 任务积分列表
	@Override
	public Result getTaskIntegralInfo(Integer user_id,String category,String ip){
		
       SupportMcc	supportMcc=supportMccService.getSupportCategoryIntegral(category, ip);
       Map<String, Object> itemMap = new HashMap<String, Object>();
       if (supportMcc == null) {
    	 log.info("未配置积分category={}",category);
    	   return new Result(ResultEnum.TASK_INTEGRAL_CONFIG_ERROR);
	   }
       
       
       if (category.equals(Const.TASK_VIDEO)&&consumeLogService.hasOverMaxVideoIntegralLimit(user_id)) { //视频超过最大积分限制
    	   //supportMcc.setIntegral(0);
    	   return new Result(ResultEnum.INTEGRAL_LIMIT_ERROR);
       }
        
       //添加新记录
       AdvertOperateLog advert=advertOperateLogService.addLuckyCreditPlay(category, user_id, supportMcc.getIntegral());
       if (advert == null) {
		   return new Result(ResultEnum.FAILED);
	   }
       
       itemMap.put("id", advert.getId());
	   itemMap.put("integral",advert.getIntegral());
	   return new Result(itemMap);
		
	}
	
	@Transactional
	@Override
	public Result finishedTask(Integer user_id,Integer id,String ip){
		
		try {
			
			if(!supportMccService.isSupportCountry(ip)){
				log.info("不支持注册国家，新闻、视频广告积分兑换");
				return new Result(ResultEnum.ILLEGAL_INTERVAL_ERROR);
			}
			
			if (consumeLogService.hasOverMaxIntegralLimit(user_id)) {
				log.info("超过当日获取积分最大限制");
				return new Result(ResultEnum.INTEGRAL_LIMIT_ERROR);
			}
			
			AdvertOperateLog play=advertOperateLogService.getLuckyCreditPlayForId(id);
			if (play == null) { //非法兑换id
				return new Result(ResultEnum.LUCKY_CREDIT_EXCHANGE_ILLEGAL);
			}
			
			if (play.getStatus().equals(Const.N)) {
				return new Result(ResultEnum.TASK_EXCHANGE_ERROR);
			}
			
			if (play.getCategory().equals(Const.TASK_VIDEO)&&consumeLogService.hasOverMaxVideoIntegralLimit(user_id)) { //视频超过最大积分限制
				//修改状态
				advertOperateLogService.updateStatus(play.getId(), Const.N,null);
				return new Result(ResultEnum.INTEGRAL_LIMIT_ERROR);
			}
			
			if (play.getIntegral().equals(0)) {
				//修改状态
				advertOperateLogService.updateStatus(play.getId(), Const.N,null);
				return new Result();
			}else {
				
				//1.帐户添加积分,添加记录
				if(userAccountService.updateAccountBlance(play.getUserId(), play.getIntegral(), true)){
					log.info("新增积分成功");
					consumeLogService.addConsumeLog(play.getUserId(), play.getCategory(), play.getCategory(),play.getIntegral(),true, null);
					//2.修改积分兑换状态
					advertOperateLogService.updateStatus(play.getId(), Const.N,null);
					return new Result();
					
				}else {
					log.error("用户新增积分失败");
					return new Result(ResultEnum.FAILED);
				}
				
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(ResultEnum.FAILED);
		}
		
		
	}
	
	
	
	
	//获取昨天签到id
	private TaskIntegral getYesterdayCheckInTask(Integer user_id) {
		
		Date nowDate = new Date();
		Date yesDate = DateUtil.addDate(nowDate, -1);
		String timeStr = DateUtil.getDateTimeString(yesDate, DateUtil.DATE_FMT);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", user_id);
		params.put("category", Const.TASK_CHECK_IN);
		params.put("startTime", timeStr+" 00:00:00");
		params.put("endTime", timeStr+" 23:59:59");
		
		return taskIntegralMapper.getPrevCheckInTask(params);
	}
	
	//获取每一周的第一天的前一天是否已签到
	private TaskIntegral getYesterdayWeekFirstdayCheckIn(Integer user_id){
		
		Date nowDate = new Date();
		Date yesDate = DateUtil.addDate(DateUtil.getFirstOfWeekDay(nowDate), -1);
		String timeStr = DateUtil.getDateTimeString(yesDate, DateUtil.DATE_FMT);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", user_id);
		params.put("category", Const.TASK_CHECK_IN);
		params.put("startTime", timeStr+" 00:00:00");
		params.put("endTime", timeStr+" 23:59:59");
		
		return taskIntegralMapper.getPrevCheckInTask(params);
	}
	
	
	//获取今天签到的id
	private Integer getTodayCheckInTask(Integer user_id) {
		
		//1.判断前一天是否已签到
		TaskIntegral prevTask = getYesterdayCheckInTask(user_id);
		if (prevTask!=null) { //前一天已签到
			
			int index = prevTask.getSort() + 1;
			if (index > 7) {
				index = 7;
			}
			return Integer.valueOf(index);
			
		}else {//前一天未签到
			return Integer.valueOf(1);
		}
	}
	
	//用户签到
	@Transactional
	@Override
	public	Result userCheckIn(Integer user_id,String ip){

		if(!supportMccService.isSupportCountry(ip)){
			log.info("非支持国家签到");
			return new Result(ResultEnum.ILLEGAL_INTERVAL_ERROR);
		}
		if (consumeLogService.hasOverMaxIntegralLimit(user_id)) {
			log.info("超过当日获取积分最大限制");
			return new Result(ResultEnum.INTEGRAL_LIMIT_ERROR);
		}
		
		//判断是否已签到
		log.info("判断是否已签到");
		if(taskLogService.hasCheckIn(user_id)){
			return new Result(ResultEnum.USER_CHECKIN);
		}
		
		
		Integer checkId = getTodayCheckInTask(user_id);
		log.info("取到今天的签到id = {}",checkId);
		if(checkId==null){
			log.info("未找到取到今天的签到id");
			return new Result(ResultEnum.FAILED);
		}
		
		TaskIntegral entity = taskIntegralMapper.get(checkId);
		if(entity==null){
			log.info("未找到签到id");
			return new Result(ResultEnum.FAILED);
		}
		
		
		
		TaskLog taskLog = new TaskLog();
		taskLog.setUserId(user_id);
		taskLog.setTaskId(checkId);
		taskLog.setIntegral(entity.getIntegral());
		taskLog.setCategory(entity.getCategory());
		taskLog.setCtime(new Date());
		if(taskLogService.addTaskLog(taskLog)){
			
			if(userAccountService.updateAccountBlance(user_id, entity.getIntegral(), true)){
				log.info("帐户添加任务积分成功");
			}else {
				log.error("帐户添加任务积分失败");
			}
			
			//添加消费记录
			consumeLogService.addConsumeLog(user_id, Const.TASK_CHECK_IN, Const.TASK_CHECK_IN,entity.getIntegral(),true, null);
			log.info("签到成功");
			Map<String, Object> rsMap = new HashMap<String, Object>();
			rsMap.put("integral", entity.getIntegral());
			return new Result(rsMap);
		}else{
			log.error("签到失败");
			return new Result(ResultEnum.FAILED);
		}
		
	}
	
	//获取用户今天签到的积分
	@Override
	public	String todayCheckInIntegral(Integer user_id){
		Integer checkId = getTodayCheckInTask(user_id);
		if(checkId==null){
			log.info("未找到取到今天的签到id");
			return null;
		}
		TaskIntegral entity = taskIntegralMapper.get(checkId);
		if(entity!=null){
			return String.format("+%d", entity.getIntegral());
		}
		log.info("未找到签到id");
		return null;
	}
	
	//获取某个用户的签到列表
	private List<TaskIntegral> getCheckInListForUserId(Integer user_id,String lang) {
		
		 Date nowDate = new Date();
	     Date firstDay = DateUtil.getFirstOfWeekDay(nowDate);
	     Date lastDay = DateUtil.getLastOfWeekDay(nowDate);
	     String currDayString = DateUtil.getDateTimeString(nowDate, DateUtil.DATE_FMT); //当前日期
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status", Const.Y);
		params.put("category", Const.TASK_CHECK_IN);
		params.put("currentTime", currDayString);
		params.put("userId", user_id);
		params.put("lang", lang);
		params.put("startTime", DateUtil.getDateTimeString(firstDay, DateUtil.DATE_FMT)+" 00:00:00");
		params.put("endTime", DateUtil.getDateTimeString(lastDay, DateUtil.DATE_FMT)+" 23:59:59");
		
		return taskIntegralMapper.getCheckInList(params);
	}
	
	//获取签到列表
	@Override
	public	Result getCheckInList(Integer user_id,String lang){
		
		//获取配置的签到列表
		/**
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("category", Const.TASK_CHECK_IN);
		params.put("status", Const.Y);
		List<TaskIntegral> checkList = taskIntegralMapper.list(params);
		**/
		List<TaskIntegral> checkList = this.getCheckInListForUserId(user_id,lang);
		
		//获取已签到的列表
	    List<TaskLog> checkedList = taskLogService.getCheckInList(user_id);
		
	    if(configSystemCache.get(Const.SYSTEM_CHECKIN_WAY) == null ||  (!StringUtil.isEmpty(configSystemCache.get(Const.SYSTEM_CHECKIN_WAY))&&configSystemCache.get(Const.SYSTEM_CHECKIN_WAY).equals("1"))){
	    	log.info("当前使用连续签到方式");
	    	//连续签到
		    //return successiveCheckInList(checkList,checkedList);
		    return successiveCheckInList(checkList,checkedList,user_id,lang);
	    }
	    log.info("当前使用非连续签到方式");
	    //非连续签到
	    return notSuccessiveCheckInList(checkList,checkedList);
      
	}
	
	//非连续签到列表算法
	private Result notSuccessiveCheckInList(List<TaskIntegral> checkList, List<TaskLog> checkedList){
		
		Date nowDate = new Date();
        Date firstDay = DateUtil.getFirstOfWeekDay(nowDate);
        String currDayString = DateUtil.getDateTimeString(nowDate, DateUtil.DATE_FMT); //当前日期
		
        boolean isTodayChecked = false;
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("checkin_days", getCheckInDay(checkedList)); //连续签到天数
		
		List<Map<String, Object>> rsList = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < checkList.size(); i++) {
			
			TaskIntegral task = checkList.get(i);
			Map<String, Object> itemMap = new HashMap<String, Object>();
			itemMap.put("name", task.getName());//说明
			
			String itemDateDay = DateUtil.getDateTimeString(DateUtil.addDate(firstDay, i), DateUtil.DATE_FMT);
			TaskLog checkLog = isCheckInList(itemDateDay,checkedList);
			itemMap.put("checked", checkLog==null?"0":"1"); //是否签到,0:未签到 1：已签到
			
			//判断当天是否已签到
			if (itemDateDay.equals(currDayString)) {
				if(itemMap.get("checked").toString().equals("1")){
					isTodayChecked = true;
				}
			}
			
			if(checkLog!=null){ //已签到
				itemMap.put("id", checkLog.getTaskId()); //签到id
				itemMap.put("desc", "+"+String.valueOf(checkLog.getIntegral()));//积分
				//itemMap.put("index", getSameCheckInId(checkLog.getTaskId(),checkList)); //取得索引
			}else{
				itemMap.put("id", task.getId()); //签到id
				itemMap.put("desc", "+"+String.valueOf(task.getIntegral()));//积分
			}
			itemMap.put("date", itemDateDay);
			if (itemDateDay.equals(currDayString)) {
				itemMap.put("is_today", "1");
			}
			rsList.add(itemMap);
			
		}
		
		rsMap.put("today_checked", isTodayChecked?"1":"0"); //判断今天是否已签到 
		rsMap.put("list", rsList);
		return new Result(rsMap);
		
	}
	
	
	//新方法 连续签到列表算法
	private Result successiveCheckInList(List<TaskIntegral> checkList, List<TaskLog> checkedList,Integer user_id,String lang){
		
		boolean isTodayChecked = taskLogService.hasCheckIn(user_id); //今天是否已签到
		Map<String, Object> rsMap = new HashMap<String, Object>();
		int check_days = taskLogService.getSuccessiveCheckInCount(user_id);
		if (isTodayChecked) {
			check_days +=1;
		}
		rsMap.put("checkin_days", check_days); //连续签到天数
		
		List<Map<String, Object>> rsList = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < checkList.size(); i++) {
			
			TaskIntegral task = checkList.get(i);
			Map<String, Object> itemMap = new HashMap<String, Object>();
			itemMap.put("name", task.getName());//说明
			itemMap.put("id", task.getId());//id
			if (check_days!=0) {
				
				if (i<=check_days-1) {
					itemMap.put("checked", "1"); //1：已签到
				}else {
					itemMap.put("checked", "0"); //2：不可点击,表示未签到
				}
			}else {
				itemMap.put("checked", "0"); //0:未签到
			}
			itemMap.put("desc", String.format("+%d", task.getIntegral()));

			rsList.add(itemMap);

		}
		
		rsMap.put("today_checked", isTodayChecked?"1":"0"); //判断今天是否已签到 
		rsMap.put("list", rsList);
		return new Result(rsMap,lang);
		
	}
	
	private int  getNotCheckInIndex(TaskIntegral task,Integer todayYmd,Map<String, Object> prevMap,List<TaskIntegral> checkList,int currIndex,TaskIntegral prevTask) {
		
		int index  = 0;
		if (Integer.valueOf(task.getYmd().replaceAll("-", "")) > todayYmd) { //大于今天
			
			if (prevMap!=null) { //前一天不为空值
				index = Integer.valueOf(prevMap.get("index").toString()) + 1;
			}else {
				index = 0;
			}
		}else { //小于今天
			
			if (prevMap!=null) { //前一天不为空值
				
				if (prevMap.get("checked").toString().equals("1")) { //已签到
					index = Integer.valueOf(prevMap.get("index").toString()) + 1;
				}else { //前一天未签到
					index = 0;
				}
				
			}else{
				
				index = 0;
				
			}
			
		}
		if (index >= checkList.size() -1) { //判断索引是否有溢出
			index = checkList.size() -1;
		}
		
		return index;
	}
	
	
	/****
	//连续签到列表算法
	private Result successiveCheckInList(List<TaskIntegral> checkList, List<TaskLog> checkedList){
		
		    Date nowDate = new Date();
	        Date firstDay = DateUtil.getFirstOfWeekDay(nowDate);
	        String currDayString = DateUtil.getDateTimeString(nowDate, DateUtil.DATE_FMT); //当前日期
			
			
			//连续签到做法
			boolean isTodayChecked = false;
			Map<String, Object> rsMap = new HashMap<String, Object>();
			rsMap.put("checkin_days", getCheckInDay(checkedList)); //连续签到天数
			
			
			List<Map<String, Object>> rsList = new ArrayList<Map<String,Object>>();
			for (int i = 0; i < checkList.size(); i++) {
				
				TaskIntegral task = checkList.get(i);
				Map<String, Object> itemMap = new HashMap<String, Object>();
				itemMap.put("name", task.getName());//说明
				
				String itemDateDay = DateUtil.getDateTimeString(DateUtil.addDate(firstDay, i), DateUtil.DATE_FMT);
				TaskLog checkLog = isCheckInList(itemDateDay,checkedList);
				itemMap.put("checked", checkLog==null?"0":"1"); //是否签到,0:未签到 1：已签到
				
				//判断当天是否已签到
				if (itemDateDay.equals(currDayString)) {
					if(itemMap.get("checked").toString().equals("1")){
						isTodayChecked = true;
					}
				}
				
				if (i==0) {
					itemMap.put("id", task.getId()); //签到id
					itemMap.put("desc", "+"+String.valueOf(task.getIntegral()));//积分
					itemMap.put("index", i);
				}else{
					
					if(checkLog!=null){ //当前是签到的
						itemMap.put("id", checkLog.getTaskId()); //签到id
						itemMap.put("desc", "+"+String.valueOf(checkLog.getIntegral()));//积分
						itemMap.put("index", getSameCheckInId(checkLog.getTaskId(),checkList)); //取得索引
					}else {
						
						
						
						//通过前一个值的index + 1 来获取值
						Map<String, Object> prevMap = rsList.get(i-1);
						
						int index = 0;
	                    if (itemDateDay.equals(currDayString)) { //今天
	                    	if (prevMap.get("checked").toString().equals("1")) { //前一天是签到的
	                    		index  = Integer.valueOf(prevMap.get("index").toString()).intValue() + 1;
							}else{ //前一天不签到
								index = 0;
							}
	                    	
						}else{
							index  = Integer.valueOf(prevMap.get("index").toString()).intValue() + 1;
						}
						//int index  = Integer.valueOf(prevMap.get("index").toString()).intValue() + 1;
						TaskIntegral nextTask = checkList.get(index);
						itemMap.put("id", nextTask.getId()); //签到id
						itemMap.put("desc", "+"+String.valueOf(nextTask.getIntegral()));//积分
						itemMap.put("index", index); 
						
					}
					
				}
				itemMap.put("date", itemDateDay);
				if (itemDateDay.equals(currDayString)) {
					itemMap.put("is_today", "1");
				}
				rsList.add(itemMap);
			}
			rsMap.put("today_checked", isTodayChecked?"1":"0"); //判断今天是否已签到 
			rsMap.put("list", rsList);
			return new Result(rsMap);
	}
	***/
	
	private int getSameCheckInId(Integer cid,List<TaskIntegral> checkList){
		
      for (int i = 0; i < checkList.size(); i++) {
			
			TaskIntegral task = checkList.get(i);
			if(task.getId().equals(cid)){
				return i;
			}
      }
      return 0;
		
	}
	
	private TaskLog isCheckInList(String ymd,List<TaskLog> checkedList){
		
		if (checkedList!=null && !checkedList.isEmpty()) {
			
			
			for (TaskLog item : checkedList) {
				
				if(DateUtil.getDateTimeString(item.getCtime(), DateUtil.DATE_FMT).equals(ymd)){
					return item;
				}
			}
			
		}
		return null;
		
	}
	
	
	//获取连续签到天数
	private int getCheckInDay(List<TaskLog> checkedList){
		if(checkedList!=null && !checkedList.isEmpty()){
			  List<Integer> maxList = new ArrayList<Integer>();
		      int curMax = 0;
		      String prveTime = null;
		      for (int i=0;i<checkedList.size();i++) {
		    	  
		    	  TaskLog item = checkedList.get(i);
		    	  if (prveTime == null) { //第一次
		    		  prveTime = DateUtil.getDateTimeString(item.getCtime(), DateUtil.DATE_FMT);
		    		  continue;
				  }
		    	  
		    	 String curTime=DateUtil.getDateTimeString(DateUtil.addDate(item.getCtime(), -1),DateUtil.DATE_FMT);
		    	 if (prveTime.equals(curTime)) {
		    		 curMax ++;
				 }else {
					if (curMax>0) {
						maxList.add(Integer.valueOf(curMax));
					}
					curMax = 0;
				 }
		    	 prveTime = DateUtil.getDateTimeString(item.getCtime(), DateUtil.DATE_FMT);
			  }
		      
		      if (curMax>0) { //最后一项
		    	  maxList.add(Integer.valueOf(curMax));
			  }
		      return this.getCheckInMax(maxList);
		}
		return 0;

	}
	
	//获取int类型数组最大值
	private  int getCheckInMax(List<Integer> arr)
	{
		
		if (arr.isEmpty()) {
			return 0;
		}
		
		int max = arr.get(0).intValue();
		for(int i=0;i<arr.size();i++)
		{
			if(arr.get(i).intValue()>max)
				max = arr.get(i).intValue();
		}
		return max+1;
	}
	
	/**
     * 从最后一次签到时间反推连续签到天数
     * 
     * @param list
     *            List<Date>
     * @param asc
     *            boolean (true:ASC,false:DESC) 对list的描述，是升序还是降序
     * @return
     * 
     * */
    private  int calcuContinue(List<Date> list, boolean asc) {
        Date end = new Date();
        Date start = new Date();
        Calendar cBefore = Calendar.getInstance();
        Calendar cAfter = Calendar.getInstance();
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        //Map<String, Object> result = new HashMap<String, Object>();

        List<Date> dateList = new ArrayList<Date>();
        if (asc == true) {
            dateList.addAll(list);
        } else {
            for (int i = list.size() - 1; i > -1; i--)
                dateList.add(list.get(i));
        }

        int size = dateList.size();
        if (size > 0) {
            end = dateList.get(size - 1);
        }
        for (int i = size - 1; i > -1; i--) {
            if (size == 1) {
                end = start = dateList.get(0);
                break;
            }
            if (i - 1 == -1) {
                break;
            }
            cBefore.setTime(dateList.get(i - 1));
            cAfter.setTime(dateList.get(i));

            if (daysBetween(cBefore.getTime(), cAfter.getTime()) == 1) {
                start = cBefore.getTime();
            } else {
                start = cAfter.getTime();
                break;
            }
        }

        /**
        result.put("start", sdf.format(start));
        result.put("end", sdf.format(end));
        result.put("continueDays", daysBetween(start, end) + 1);
        ***/
        return daysBetween(start, end) + 1;
    }

    /**
     * 计算两个日期之间相差的天数，忽略时分秒 例如：2014年12月31日 与 2015年1月1日 相差1天
     * 
     * @param before
     * @param after
     * @return 间隔天数
     */
    private  int daysBetween(Date before, Date after) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            before = sdf.parse(sdf.format(before));
            after = sdf.parse(sdf.format(after));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long days_long = (after.getTime() - before.getTime())
                / (1000 * 60 * 60 * 24);
        return Integer.parseInt(String.valueOf(days_long));
    }

}
